package Thread;

public class Demo12 {
//    有三个线程，分别只能打印A，B和C
//    要求按顺序打印ABC，打印10次

    private static Object locker = new Object();
    private static int state = 1;

    public static void main(String[] args) throws InterruptedException {
        //通过state这个变量作为判断条件,不满足该条件的线程进入等待,满足条件的线程则先打印,
        //然后改变条件,通过notify唤醒其他线程,继续判断,打印;
        for (int i = 0; i < 10; i++) {
            Thread thread1 = new Thread(() -> {
                synchronized (locker) {
                    while(state != 1) {
                        try {
                            locker.wait();
                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("A");
                    state = 2;
                    locker.notify();
                }
            });

            Thread thread2 = new Thread(() -> {
                synchronized (locker) {
                    while(state != 2) {
                        try {
                            locker.wait();
                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("B");
                    state = 3;
                    locker.notify();
                }
            });

            Thread thread3 = new Thread(() -> {
                synchronized (locker) {
                    while(state != 3) {
                        try {
                            locker.wait();
                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("C");
                    state = 1;
                    locker.notify();
                }
            });

            thread1.start();
            thread2.start();
            thread3.start();
            thread1.join();
            thread2.join();
            thread3.join();
        }
    }
}

